import { SlateEditor, SlateElement, SlateTransforms } from '@wangeditor/editor';
import { PAGEPAD_TYPE } from './index';

// 菜单 key
export const MENU_KEY = 'pagePad';
// 菜单名
export const MENU_NAME = '页边距';

class menu {
  constructor(editor) {
    this.editor = editor;
    this.title = '页边距';
    this.iconSvg = '<svg viewBox="0 0 1024 1024"><path d="M498.7 655.8l-197.6-268c-8.1-10.9-0.3-26.4 13.3-26.4h395.2c13.6 0 21.4 15.4 13.3 26.4l-197.6 268c-6.6 9-20 9-26.6 0z"></path></svg>';
    this.tag = 'select';
    this.margin = '0px';
    this.selectDom = null;
    this.selectedValue = '1';
  }

  // 获取选项数组
  getOptions(editor) {
    const currentValue = this.getValue(editor);

    const options = [
      {
        value: '1',
        text: '1',
        selected: this.selectedValue === '1',
      },
      { value: '2', text: '2', selected: this.selectedValue === '2' },
      { value: '3', text: '3', selected: this.selectedValue === '3' },
    ];
    return options;
  }

  // 菜单是否需要激活（如选中加粗文本，“加粗”菜单会激活），用不到则返回 false
  isActive(editor) {
    return false;
  }

  // 获取菜单执行时的 value ，用不到则返回空 字符串或 false
  getValue(editor) {
    return this.selectedValue;
  }

  // 菜单是否需要禁用（如选中 H1 ，“引用”菜单被禁用），用不到则返回 false
  isDisabled(editor) {
    return false;
  }

  // 弹出框 modal 的定位：1. 返回某一个 SlateNode； 2. 返回 null （根据当前选区自动定位）
  getModalPositionNode(editor) {
    return null; // modal 依据选区定位
  }

  // 定义 modal 内部的 DOM Element
  getModalContentElem(editor) {
    return null; // 不需要模态框
  }

  // 执行菜单操作
  exec(editor, value) {
    this.selectedValue = value;
    this.margin = value * 16 + 'px';
    editor.restoreSelection();

    const nodeEntries = Array.from(SlateEditor.nodes(editor, {
      match: (node) => {
        if (node && SlateElement.isElement(node)) {
          return true;
        }
        return false;
      },
      universal: true
    }));

    const newMargin = `${value * 16}px`; // 假设使用 
    const children = [];
    if (!nodeEntries) {
      children.push({ text: '' });
    } else {
      for (const nodeEntry of nodeEntries) {
        const [node] = nodeEntry;
        children.push(node);
      }
    }
    console.log(this.margin, 'PAGEPAD_TYPE');

    const targetNode = {
      type: 'pagePad',
      margin: this.margin,
      children
    };
    console.log("🚀 ~ menu ~ exec ~ targetNode:", targetNode);

    SlateTransforms.setNodes(editor, targetNode, { mode: 'highest' });
    editor.updateView();
    editor.hidePanelOrModal();
  }


  // 获取下拉框 DOM 元素
  getSelectDom() {
    return this.selectDom;
  }
}

// 自定义菜单配置
export const menuConfig = {
  key: MENU_KEY,
  factory(editor) {
    return new menu(editor);
  }
};